import { useState } from "react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { 
  BarChart, 
  Bar, 
  XAxis, 
  YAxis, 
  CartesianGrid, 
  Tooltip, 
  ResponsiveContainer,
  PieChart,
  Pie,
  Cell
} from 'recharts';
import { 
  TrendingUp, 
  TrendingDown, 
  Users, 
  BookOpen, 
  Clock, 
  AlertTriangle,
  Download,
  Filter,
  Calendar,
  User
} from "lucide-react";

// Mock data for demonstration
const mockClassData = {
  class_id: "CLASS_001",
  average_completion_rate: 78,
  total_students: 24,
  active_students: 19,
  underperforming_students: 3
};

const mockStudentMetrics = [
  {
    student_id: "STU_001",
    name: "Alice Johnson",
    group_id: "GROUP_A",
    engagement_score: 92,
    last_active: "2024-01-15T10:30:00Z",
    low_engagement_flag: false,
    completion_rate: 85
  },
  {
    student_id: "STU_002", 
    name: "Bob Chen",
    group_id: "GROUP_B",
    engagement_score: 45,
    last_active: "2024-01-12T14:20:00Z",
    low_engagement_flag: true,
    completion_rate: 32
  },
  {
    student_id: "STU_003",
    name: "Carol Williams",
    group_id: "GROUP_A", 
    engagement_score: 78,
    last_active: "2024-01-15T09:15:00Z",
    low_engagement_flag: false,
    completion_rate: 72
  },
  {
    student_id: "STU_004",
    name: "David Brown",
    group_id: "GROUP_C",
    engagement_score: 38,
    last_active: "2024-01-10T16:45:00Z",
    low_engagement_flag: true,
    completion_rate: 28
  }
];

const mockModuleUsage = [
  {
    module_id: "MOD_001",
    module_title: "PBL Case: Climate Change Solutions",
    module_type: "PBL",
    view_count: 156,
    interaction_count: 89,
    completion_status: "Completed",
    time_spent_minutes: 45,
    completion_rate: 78
  },
  {
    module_id: "MOD_002",
    module_title: "Lesson Plan Generator",
    module_type: "Template",
    view_count: 203,
    interaction_count: 145,
    completion_status: "In Progress",
    time_spent_minutes: 32,
    completion_rate: 85
  },
  {
    module_id: "MOD_003",
    module_title: "Smart Courseware Assembly",
    module_type: "Courseware",
    view_count: 98,
    interaction_count: 67,
    completion_status: "Not Started",
    time_spent_minutes: 12,
    completion_rate: 42
  }
];

const mockAIInsights = [
  {
    type: "warning",
    title: "Low Engagement Alert",
    description: "3 students have not accessed materials in the past 5 days",
    recommendation: "Consider sending personalized check-in messages or scheduling 1-on-1 sessions"
  },
  {
    type: "success", 
    title: "High Performance Module",
    description: "Lesson Plan Generator has 85% completion rate",
    recommendation: "Share this module's success patterns with other course materials"
  },
  {
    type: "info",
    title: "Usage Pattern",
    description: "Most activity occurs between 2-4 PM",
    recommendation: "Schedule live sessions during peak engagement hours"
  }
];

const engagementChartData = [
  { day: 'Mon', engagement: 78 },
  { day: 'Tue', engagement: 85 },
  { day: 'Wed', engagement: 72 },
  { day: 'Thu', engagement: 90 },
  { day: 'Fri', engagement: 68 },
  { day: 'Sat', engagement: 45 },
  { day: 'Sun', engagement: 52 }
];

const moduleTypeData = [
  { name: 'PBL Cases', value: 35, color: '#8884d8' },
  { name: 'Templates', value: 45, color: '#82ca9d' },
  { name: 'Courseware', value: 20, color: '#ffc658' }
];

export function ClassroomAnalytics() {
  const [selectedClass, setSelectedClass] = useState("all");
  const [selectedStudent, setSelectedStudent] = useState("all");
  const [selectedModule, setSelectedModule] = useState("all");
  const [dateRange, setDateRange] = useState("7days");

  const handleExportReport = () => {
    console.log("Exporting class report...");
    // Implementation would generate PDF/Excel report
  };

  return (
    <div className="space-y-6">
      {/* Header with Filters */}
      <div className="flex flex-col lg:flex-row gap-4 items-start lg:items-center justify-between">
        <div>
          <h2 className="text-2xl font-bold text-gray-900">Dashboard</h2>
          <p className="text-gray-600 mt-1">Track student progress and engagement across learning modules</p>
        </div>
        <Button onClick={handleExportReport} className="bg-blue-600 hover:bg-blue-700">
          <Download className="w-4 h-4 mr-2" />
          Export Dashboard Report
        </Button>
      </div>

      {/* Filter Controls */}
      <Card>
        <CardHeader>
          <CardTitle className="flex items-center gap-2">
            <Filter className="w-5 h-5" />
            Filters
          </CardTitle>
        </CardHeader>
        <CardContent>
          <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">Class</label>
              <Select value={selectedClass} onValueChange={setSelectedClass}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Classes</SelectItem>
                  <SelectItem value="class1">Biology AP</SelectItem>
                  <SelectItem value="class2">Chemistry 101</SelectItem>
                  <SelectItem value="class3">Physics Honors</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">Student</label>
              <Select value={selectedStudent} onValueChange={setSelectedStudent}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Students</SelectItem>
                  <SelectItem value="stu1">Alice Johnson</SelectItem>
                  <SelectItem value="stu2">Bob Chen</SelectItem>
                  <SelectItem value="stu3">Carol Williams</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">Module Type</label>
              <Select value={selectedModule} onValueChange={setSelectedModule}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">All Modules</SelectItem>
                  <SelectItem value="pbl">PBL Cases</SelectItem>
                  <SelectItem value="template">Templates</SelectItem>
                  <SelectItem value="courseware">Courseware</SelectItem>
                </SelectContent>
              </Select>
            </div>
            <div>
              <label className="text-sm font-medium text-gray-700 mb-2 block">Date Range</label>
              <Select value={dateRange} onValueChange={setDateRange}>
                <SelectTrigger>
                  <SelectValue />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="7days">Last 7 Days</SelectItem>
                  <SelectItem value="30days">Last 30 Days</SelectItem>
                  <SelectItem value="90days">Last 90 Days</SelectItem>
                  <SelectItem value="semester">This Semester</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* Summary Cards */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-6">
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Total Students</p>
                <p className="text-2xl font-bold">{mockClassData.total_students}</p>
              </div>
              <Users className="w-8 h-8 text-blue-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Active Students</p>
                <p className="text-2xl font-bold text-green-600">{mockClassData.active_students}</p>
              </div>
              <TrendingUp className="w-8 h-8 text-green-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Avg Completion Rate</p>
                <p className="text-2xl font-bold">{mockClassData.average_completion_rate}%</p>
              </div>
              <BookOpen className="w-8 h-8 text-purple-500" />
            </div>
          </CardContent>
        </Card>
        
        <Card>
          <CardContent className="p-6">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm text-gray-600">Need Attention</p>
                <p className="text-2xl font-bold text-red-600">{mockClassData.underperforming_students}</p>
              </div>
              <AlertTriangle className="w-8 h-8 text-red-500" />
            </div>
          </CardContent>
        </Card>
      </div>

      <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
        {/* Engagement Chart */}
        <Card>
          <CardHeader>
            <CardTitle>Weekly Engagement Trends</CardTitle>
            <CardDescription>Daily engagement scores across the week</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <BarChart data={engagementChartData}>
                <CartesianGrid strokeDasharray="3 3" />
                <XAxis dataKey="day" />
                <YAxis />
                <Tooltip />
                <Bar dataKey="engagement" fill="#8884d8" />
              </BarChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>

        {/* Module Usage Distribution */}
        <Card>
          <CardHeader>
            <CardTitle>Module Usage Distribution</CardTitle>
            <CardDescription>Breakdown of student activity by module type</CardDescription>
          </CardHeader>
          <CardContent>
            <ResponsiveContainer width="100%" height={300}>
              <PieChart>
                <Pie
                  data={moduleTypeData}
                  cx="50%"
                  cy="50%"
                  labelLine={false}
                  label={({ name, percent }) => `${name} ${(percent * 100).toFixed(0)}%`}
                  outerRadius={80}
                  fill="#8884d8"
                  dataKey="value"
                >
                  {moduleTypeData.map((entry, index) => (
                    <Cell key={`cell-${index}`} fill={entry.color} />
                  ))}
                </Pie>
                <Tooltip />
              </PieChart>
            </ResponsiveContainer>
          </CardContent>
        </Card>
      </div>

      {/* AI Insights */}
      <Card>
        <CardHeader>
          <CardTitle>AI-Powered Insights & Recommendations</CardTitle>
          <CardDescription>Intelligent analysis of student behavior and teaching suggestions</CardDescription>
        </CardHeader>
        <CardContent>
          <div className="space-y-4">
            {mockAIInsights.map((insight, index) => (
              <div key={index} className="border rounded-lg p-4">
                <div className="flex items-start gap-3">
                  <div className={`w-2 h-2 rounded-full mt-2 ${
                    insight.type === 'warning' ? 'bg-yellow-500' :
                    insight.type === 'success' ? 'bg-green-500' : 'bg-blue-500'
                  }`} />
                  <div className="flex-1">
                    <h4 className="font-medium text-gray-900">{insight.title}</h4>
                    <p className="text-sm text-gray-600 mt-1">{insight.description}</p>
                    <p className="text-sm text-blue-600 mt-2 font-medium">💡 {insight.recommendation}</p>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </CardContent>
      </Card>

      {/* Student Performance Table */}
      <Card>
        <CardHeader>
          <CardTitle>Student Performance Overview</CardTitle>
          <CardDescription>Individual student metrics and engagement levels</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Student Name</TableHead>
                <TableHead>Group</TableHead>
                <TableHead>Engagement Score</TableHead>
                <TableHead>Completion Rate</TableHead>
                <TableHead>Last Active</TableHead>
                <TableHead>Status</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {mockStudentMetrics.map((student) => (
                <TableRow key={student.student_id}>
                  <TableCell className="font-medium">{student.name}</TableCell>
                  <TableCell>{student.group_id}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <span>{student.engagement_score}</span>
                      <div className="w-16 h-2 bg-gray-200 rounded-full">
                        <div 
                          className="h-2 bg-blue-500 rounded-full" 
                          style={{ width: `${student.engagement_score}%` }}
                        />
                      </div>
                    </div>
                  </TableCell>
                  <TableCell>{student.completion_rate}%</TableCell>
                  <TableCell>{new Date(student.last_active).toLocaleDateString()}</TableCell>
                  <TableCell>
                    {student.low_engagement_flag ? (
                      <Badge variant="destructive">Needs Attention</Badge>
                    ) : (
                      <Badge variant="default" className="bg-green-100 text-green-800">Active</Badge>
                    )}
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {/* Module Performance Table */}
      <Card>
        <CardHeader>
          <CardTitle>Module Performance</CardTitle>
          <CardDescription>Usage statistics and completion rates by module</CardDescription>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>Module Title</TableHead>
                <TableHead>Type</TableHead>
                <TableHead>Views</TableHead>
                <TableHead>Interactions</TableHead>
                <TableHead>Avg Time (min)</TableHead>
                <TableHead>Completion Rate</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {mockModuleUsage.map((module) => (
                <TableRow key={module.module_id}>
                  <TableCell className="font-medium">{module.module_title}</TableCell>
                  <TableCell>
                    <Badge variant="outline">{module.module_type}</Badge>
                  </TableCell>
                  <TableCell>{module.view_count}</TableCell>
                  <TableCell>{module.interaction_count}</TableCell>
                  <TableCell>{module.time_spent_minutes}</TableCell>
                  <TableCell>
                    <div className="flex items-center gap-2">
                      <span>{module.completion_rate}%</span>
                      <div className="w-16 h-2 bg-gray-200 rounded-full">
                        <div 
                          className="h-2 bg-green-500 rounded-full" 
                          style={{ width: `${module.completion_rate}%` }}
                        />
                      </div>
                    </div>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>
    </div>
  );
}
